<?php

namespace App\Listeners;

use App\Events\Consumption;
use App\Level;
use App\User;
use App\UserLevel;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class HandleConsumption
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Consumption  $event
     * @return void
     */
    public function handle(Consumption $event)
    {
        $order = $event->order;
        if ($order && $order->pay_status == 1 && $order->order_amount > 0 ) {
            $user = User::find($order->user_id);
            $levels = Level::orderBy('id', 'desc')->get();
            $user->consumption_count = $user->consumption_count + $order->order_amount;
            foreach ($levels as $level) {
                if ( $user->consumption_count >= $level->condition && $user->level_id < $level->id) {
                    $user->level_id = $level->id;
                    break;
                }
            }
            $user->save();
        }
    }
}